﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace blackhouse.Web {
	public class PageUrl {

		#region Fields

		private bool invalidContext = false;
		private NameValueCollection parameters;

		#endregion

		#region Constructors

		public PageUrl() {
			if(HttpContext.Current == null)
				this.invalidContext = true;
			if(HttpContext.Current.Request == null)
				this.invalidContext = true;

			if(!invalidContext) {
				this.parameters = this.getCurrentRequestParameters();
			}
		}

		#endregion

		#region Methods

		public void AddParameter(string key, string value) {
			if(this.invalidContext) return;
			this.parameters[key] = value;
		}

		public void RemoveParameter(string key) {
			if(this.invalidContext) return;
			this.parameters.Remove(key);
		}

		public string GetParameter(string key) {
			return this.parameters[key];
		}

		public string GetUrl() {
			if(this.invalidContext) return "";

			string rawUrl = HttpContext.Current.Request.RawUrl;
			int indexof = rawUrl.IndexOf('?');
			if(indexof > 0)
				rawUrl = rawUrl.Substring(0, indexof);
			List<string> pp = new List<string>();
			foreach(string key in parameters.AllKeys)
				pp.Add(string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(parameters[key])));


			return rawUrl + "?" + string.Join("&", pp.ToArray());
		}

		private NameValueCollection getCurrentRequestParameters() {
			Page page = HttpContext.Current.Handler as Page;
			if(page != null) {
				if(page.Items["page_url"] == null || !(page.Items["page_url"] is NameValueCollection)) {
					NameValueCollection nvc = this.parseCurrentRequestParameters();
					page.Items["page_url"] = nvc.MakeCopy();
					return nvc;
				} else {
					NameValueCollection nvc = page.Items["page_url"] as NameValueCollection;
					if(nvc != null) return nvc.MakeCopy();
					else return new NameValueCollection();
				}
			} else {
				return this.parseCurrentRequestParameters();
			}
		}

		private NameValueCollection parseCurrentRequestParameters() {
			NameValueCollection nvc = new NameValueCollection();

			string rawUrl = HttpContext.Current.Request.RawUrl;
			Regex rx = new Regex("([^?=&]+)(=([^&]*))?");
			MatchCollection mc = rx.Matches(rawUrl);
			foreach(Match m in mc) {
				if(m.Groups[1].Success && m.Groups[3].Success)
					nvc.Add(m.Groups[1].Value, m.Groups[3].Value);
			}

			return nvc;
		}

		#endregion

	}
}